package com.ncd.form.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ncd.common.core.text.Convert;
import com.ncd.common.utils.DateUtils;
import com.ncd.common.utils.ShiroUtils;
import com.ncd.form.domain.FormDict;
import com.ncd.form.domain.LayoutVersion;
import com.ncd.form.domain.Record;
import com.ncd.form.domain.RecordItm;
import com.ncd.form.mapper.FormDictMapper;
import com.ncd.form.mapper.LayoutVersionMapper;
import com.ncd.form.mapper.RecordItmMapper;
import com.ncd.form.mapper.RecordMapper;
import com.ncd.form.result.RecordResult;
import com.ncd.form.service.IRecordItmService;
import com.ncd.form.service.IRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RecordServiceIml extends ServiceImpl<RecordMapper, Record> implements IRecordService {

    @Resource
    LayoutVersionMapper layoutVersionMapper;

    @Resource
    RecordItmMapper recordItmMapper;

    @Resource
    FormDictMapper formDictMapper;

    @Resource
    IRecordItmService recordItmService;

    @Override
    public List<RecordResult> queryList(RecordResult recordResult) {

        //构造条件
        QueryWrapper<Record> wrapper = new QueryWrapper<>();

        wrapper.like(StrUtil.isNotBlank(recordResult.getLayoutName()),"t2.layout_name",recordResult.getLayoutName());

        wrapper.orderByDesc("t1.record_date");

        return this.baseMapper.queryList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveRecord(JSONObject jsonParam) {
        JSONArray rowJSONArr=jsonParam.getJSONArray("rows");
        Long recordId=jsonParam.getLong("recordId");

        if((null==recordId)||(0==recordId.intValue())){
            Long versionId=jsonParam.getLong("versionId");

            LayoutVersion layoutVersion=layoutVersionMapper.selectById(versionId);
            Record record=new Record();
            record.setLayoutId(layoutVersion.getLayoutId());
            record.setRecordVersionId(versionId);
            record.setRecordUser(ShiroUtils.getUserId());
            record.setRecordDate(DateUtils.getNowDate());
            this.baseMapper.insert(record);
            recordId=record.getRecordId();
        }else{
            recordItmMapper.delete(new LambdaUpdateWrapper<RecordItm>()
                    .eq(RecordItm::getRecordId,recordId));
        }
        List<RecordItm> recordItms=new ArrayList<>();
        for(int i=0;i<rowJSONArr.size();i++){
            JSONObject json=rowJSONArr.getJSONObject(i);
            String dictStr=json.getString("name");
            String rowKey="";
            String dictType="";
            Long dictId=0L;
            if(dictStr.indexOf("-")>=0){
                String[] strArr=dictStr.split("-");
                dictId=Long.valueOf(strArr[0]);
                if(strArr.length==2){
                    if(StrUtil.isNumeric(strArr[1])){
                        rowKey=strArr[1];
                    }else{
                        dictType=strArr[1];
                    }
                }
                if(strArr.length==3){
                    rowKey=strArr[1];
                    dictType=strArr[2];
                }
            }else{
                dictId=Long.valueOf(dictStr);
            }
            if(StrUtil.isBlank(dictType)){
                FormDict dict=formDictMapper.selectById(dictId);
                dictType=dict.getDictType();
            }

            RecordItm recordItm=new RecordItm();
            recordItm.setRecordId(recordId);
            recordItm.setDictId(dictId);
            recordItm.setRowKey(rowKey);
            if(("radio".equals(dictType))||("checkbox".equals(dictType))||("select".equals(dictType))){
                String value=json.getString("value");
                recordItm.setValueDict(value);
            }else{
                String value=json.getString("value");
                recordItm.setValue(value);
            }
            recordItms.add(recordItm);
        }
        recordItmService.saveBatch(recordItms);
        return recordId.intValue();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(String ids) {
        List<Long> idList= Convert.toLongList(ids);
        this.baseMapper.delete(new LambdaQueryWrapper<Record>().in(Record::getRecordId,idList));
        recordItmMapper.delete(new LambdaQueryWrapper<RecordItm>().in(RecordItm::getRecordId,idList));
        return true;
    }
}
